/**
 * Created by ShaunJ on 16/12/12.
 */
"use strict";
angular.module(moduleName + '.directives')
    .directive('hrDatePicker', ['$ionicPopup', '$timeout','CommonDaterService','$ionicScrollDelegate','$ionicModal', function ($ionicPopup, $timeout,CommonDaterService, $ionicScrollDelegate,$ionicModal) {
        return {
            restrict: 'AE',
            $scope: true,
            template:  '<input type="text"  placeholder={{vm.placeholder}} ng-model="datedata"  class="{{vm.cssClass}} datapicker" readonly>',
            scope: {
                datedata: '=',
                startdate: '@',
                enddate:'@',
                hourstart:'@',
                hourend:'@',
                backdrop:'@',
                datetype:'@',
                timearea:'@',
                backdropClickToClose:'@',
                buttonClicked: '&'
            },
            replace:true,
            link: function (scope, element, attrs) {
                CommonDaterService.init(attrs.startdate,attrs.enddate,attrs.hourstart,attrs.hourend);
                var vm=scope.vm={},newdatepickerModel=null;
                var tempData = '';
                var originalDate = scope.datedata ? scope.datedata: '';
                vm.datetype = attrs.datetype=='true' ? true:false;
                vm.timearea = attrs.timearea=='true' ? true:false;
                vm.yearHandle="yearHandle"+attrs.datedata;
                vm.monthHandle="monthHandle"+attrs.datedata;
                vm.dateHandle="dateHandle"+attrs.datedata;
                vm.hourHandle="hourHandle"+attrs.datedata;
                vm.minHandle="minHandle"+attrs.datedata;
                vm.placeholder=attrs.placeHolder || "请选择日期";
                vm.okText=attrs.okText || "确定";
                vm.cssClass=attrs.cssClass;
                vm.backdrop=scope.$eval(scope.backdrop) || false;
                vm.backdropClickToClose=scope.$eval(scope.backdropClickToClose) || false;
                // vm.yearArr= attrs.datetype=='true' ? CommonDaterService.dataListTwo:CommonDaterService.dataListThree;
                vm.yearArr = CommonDaterService.yearArr;
                vm.monthArr = CommonDaterService.monthArr;
                vm.dateArr = [];
                vm.hourArr = CommonDaterService.hourArr;
                vm.minArr = CommonDaterService.minArr;
                vm.tag=attrs.tag || "-";
                vm.returnOk=function(){
                    scope.datedata = tempData;
                    newdatepickerModel && newdatepickerModel.hide();
                    scope.buttonClicked && scope.buttonClicked();
                }
                vm.clickToClose=function(){
                    scope.datedata = originalDate;
                    vm.backdropClickToClose && newdatepickerModel && newdatepickerModel.hide();
                }


                vm.getData=function(name){

                    $timeout.cancel(vm.scrolling);//取消之前的scrollTo.让位置一次性过渡到最新
                    $timeout.cancel(vm.dataing);//取消之前的数据绑定.让数据一次性过渡到最新
                    switch(name)
                    {
                        case 'year':
                            if (!vm.yearArr) return false;
                            var year=true,length=vm.yearArr.length,Handle=vm.yearHandle;
                            break;
                        case 'month':
                            if (!vm.monthArr) return false;
                            var month=true,length=vm.monthArr.length,Handle=vm.monthHandle;
                            break;
                        case 'date':
                            if (!vm.dateArr) return false;
                            var date=true,Handle=vm.dateHandle,length=vm.dateArr.length;
                            break;
                        case 'hour':
                            if (!vm.hourArr) return false;
                            var hour=true,length=vm.hourArr.length,Handle=vm.hourHandle;
                            break;
                        case 'min':
                            if (!vm.minArr) return false;
                            var min=true,Handle=vm.minHandle,length=vm.minArr.length;
                            break;
                    }
                    var top= $ionicScrollDelegate.$getByHandle(Handle).getScrollPosition().top;//当前滚动位置

                    var index = Math.round(top / 36);
                    //console.log(index,length);
                    if (index < 0 ) index =0;//iOS bouncing超出头
                    if (index >length-1 ) index =length-1;//iOS bouncing超出尾
                    if (top===index*36 ) {
                        vm.dataing=$timeout(function () {
                            year && (vm.year=vm.yearArr[index]);
                            month &&  (vm.month=vm.monthArr[index]);
                            date &&  (vm.date=vm.dateArr[index]);
                            hour && (vm.hour=vm.hourArr[index]);
                            min && (vm.min=vm.minArr[index]);
                            if(year || month){
                              vm.getDateLoop(vm.year,vm.month)
                            }
                            //数据同步
                            if(!vm.datetype && vm.timearea)
                                tempData=vm.year +vm.tag+  vm.month+vm.tag+vm.date+'\ '+vm.hour+':'+vm.min ;
                            else
                                (!vm.datetype) ? (tempData=vm.year +vm.tag+  vm.month+vm.tag+vm.date ) :(tempData=vm.year +vm.tag+  vm.month)

                        },150)
                    }else{
                        vm.scrolling=$timeout(function () {
                            $ionicScrollDelegate.$getByHandle(Handle).scrollTo(0,index*36,true);
                        },150)
                    }
                    //}

                }

                //获取"日"滚轮天数
                vm.getDateLoop = function (year,month) {
                    var dataArrTemp = [];
                    for(var loop = 0; loop < 10; loop++) {
                      var yearTemp = year;
                      var monthTemp = month;
                      var monthDate = 0;
                      switch (monthTemp) {
                        case '01':
                        case '03':
                        case '05':
                        case '07':
                        case '08':
                        case '10':
                        case '12':
                          monthDate = 31;
                          break;
                        case '02':
                          monthDate = 28;
                          break;
                        default:
                          monthDate = 30;
                          break
                      }
                      if (monthTemp == '02') {
                        if (yearTemp % 4 == 0) {
                          monthDate = 29
                        } else {
                          monthDate = 28
                        }
                      }

                      for (var k = 1; k <= monthDate; k++) {
                        var tempData = '';
                        if (k < 10) {
                          tempData = '0' + k;
                        } else {
                          tempData = k;
                        }
                        dataArrTemp.push(tempData);
                      }
                    }
                    vm.dateArr = dataArrTemp;
                    $ionicScrollDelegate.$getByHandle(vm.dateHandle).scrollTo(0,5*monthDate*36,true);

                };
                vm.init=function(){

                    //初始状态下滚动位置
                    var inityearIndex= 0,
                        initmonthIndex= 0,
                        initdateIndex=0;

                    var inithourIndex=0,
                        initminIndex=0;


                    //获取初始值的位置
                    if(scope.datedata){
                        var values = '';
                        if(scope.datedata.length<=10){
                            values = scope.datedata.split('-');
                        } else{
                            values = scope.datedata.substr(0,10).split('-');
                            values.push(scope.datedata.substr(11,2));
                            values.push(scope.datedata.substr(14,2));
                        }
                        //设置"date"滚轮
                        vm.getDateLoop(values[0],values[1]);

                        for(var i= 0;i<vm.yearArr.length;i++){
                            if(vm.yearArr[i] == values[0]){
                                inityearIndex =i;
                                break;
                            }
                        }

                        for(var i= 0;i<vm.monthArr.length;i++){
                            if(vm.monthArr[i] == values[1]){
                                initmonthIndex =i;
                                break;
                            }
                        }

                        if(values.length>2){
                            for(var i= 0;i<vm.dateArr.length;i++){
                                if(vm.dateArr[i] == values[2]){
                                    initdateIndex =i;
                                    break;
                                }
                            }
                        }

                        if(values.length>3){
                            for(var i= 0;i<vm.hourArr.length;i++){
                                if(vm.hourArr[i] == values[3]){
                                    inithourIndex =i;
                                    break;
                                }
                            }
                            for(var i= 0;i<vm.minArr.length;i++){
                                if(vm.minArr[i] == values[4]){
                                    initminIndex =i;
                                    break;
                                }
                            }
                        }
                    }

                    vm.year=vm.yearArr[inityearIndex];
                    vm.month=vm.monthArr[initmonthIndex];
                    vm.date=vm.dateArr[initdateIndex];
                    vm.hour=vm.hourArr[inithourIndex];
                    vm.min=vm.minArr[initminIndex];

                    if(!scope.datedata){
                        scope.datedata=vm.year +vm.tag+  vm.month
                    }

                    //滚动到对应位置
                    $ionicScrollDelegate.$getByHandle(vm.yearHandle).scrollTo(0,inityearIndex*36,true);
                    $ionicScrollDelegate.$getByHandle(vm.monthHandle).scrollTo(0,5*12*36+initmonthIndex*36,true);
                    $ionicScrollDelegate.$getByHandle(vm.dateHandle).scrollTo(0,5*31*36+initdateIndex*36,true);
                    $ionicScrollDelegate.$getByHandle(vm.hourHandle).scrollTo(0,5*24*36+inithourIndex*36,true);
                    $ionicScrollDelegate.$getByHandle(vm.minHandle).scrollTo(0,5*60*36+initminIndex*36,true);

                }


                element.on("click", function () {
                    //零时处理 点击过之后直接显示不再创建
                    if (!attrs.checked) {
                        newdatepickerModel && newdatepickerModel.remove();
                    }else{
                        vm.init();
                        newdatepickerModel && newdatepickerModel.show();
                        return
                    }
                    attrs.checked=true;
                    $ionicModal.fromTemplateUrl('hr-date-picker/hr-date-picker.html', {
                        scope: scope,
                        animation: 'slide-in-up',
                        backdropClickToClose:vm.backdropClickToClose
                    }).then(function(modal) {
                        newdatepickerModel = modal;
                        //初始化 先获取数据后展示
                        $timeout(function () {
                            //vm.getData('year');
                            vm.init();  //用新的init方法取代旧的
                            newdatepickerModel.show();
                        },100)
                    })
                })
                //销毁模型
                scope.$on('$destroy', function() {
                    newdatepickerModel && newdatepickerModel.remove();
                });
            }
        }
    }]);
